package com.darksider.darkotlin.ui.main

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.darksider.darkotlin.R
import com.darksider.darkotlin.bean.Car
import com.darksider.darkotlin.net.Net
import com.darksider.darkotlin.ui.adapter.SimpleRVAdater
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initData()

    }

    lateinit var carAdapter: SimpleRVAdater

    private fun initData() {
        Net.api.getAllCar("120.318883", "30.188883", "5000000")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { (Result, Cars) ->
                    when (Result) {
                        0 -> {
                            if (Cars.isNotEmpty()) {
                                initList(Cars)
                            } else
                                toast("没有车辆数据")
                        }
                        else -> {
                            toast("获取数据失败")
                        }
                    }
                }
    }

    private fun initList(cars: List<Car>) {
        tv_main_car_num.text = cars.size.toString()
        carAdapter = SimpleRVAdater(cars) {
            view: View, position: Int ->
            toast("Position is $position")
        }
        val linearManager = LinearLayoutManager(this)
        linearManager.orientation = LinearLayoutManager.VERTICAL
        rv_main_name_list.layoutManager = linearManager
        carAdapter.refreshData(cars)
        rv_main_name_list.adapter = carAdapter
    }
}
